﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MethodWorx.CMS.Plugins;
using MethodWorx.CMS.UI.Models;
using MethodWorx.CMS.Services;
using MethodWorx.CMS.Membership;
using MethodWorx.CMS.UI.Areas.Dashboard.Models;

namespace MethodWorx.CMS.UI.Areas.Dashboard.Controllers
{
    public class DashboardController : Controller
    {
        private IPluginRepository plugins;
        private UserService users;

        public DashboardController(IPluginRepository plugins, UserService users)
        {
            this.plugins = plugins;
            this.users = users;
            
        }

        [HttpGet]
        public ActionResult Index()
        {
            var user = this.users.GetUserById(Guid.Parse(this.User.Identity.Name));
            return View(new DashboardModel(user, this.plugins));
        }

        [HttpPost]
        public ActionResult Index(Guid plugin, Guid [] widgets, string submit)
        {
            var user = this.users.GetUserById(Guid.Parse(this.User.Identity.Name));
            if (submit == "apply")
            {
                //
                //  ok, find the plugin
                var foundPlugin = this.plugins.All().OfType<SafePlugin>().FirstOrDefault(p => p.Id == plugin);
                if (foundPlugin != null)
                {
                    var result = foundPlugin.Invoke<IDashboardPlugin, IEnumerable<DashboardWidget>>(t => t.GetWidgets()).Where(dw => widgets != null && widgets.Contains(dw.Id)).ToArray();
                    users.SetDashboardWidgets(users.GetUserById(Guid.Parse(User.Identity.Name)), foundPlugin, result);
                }
            }
            return View(new DashboardModel(user, this.plugins));
        }

        public ActionResult GetWidgets(Guid id)
        {
            //
            //  ok, find the plugin
            var plugin = this.plugins.All().OfType<SafePlugin>().FirstOrDefault(p => p.Id == id);
            if (plugin != null)
            {
                var user = this.users.GetUserById(Guid.Parse(this.User.Identity.Name));
                var result = plugin.Invoke<IDashboardPlugin, IEnumerable<DashboardWidget>>(t => t.GetWidgets()).Select(i => new
                        {
                            Id = i.Id,
                            Title = i.Title,
                            Selected = user.DashboardWidgets.Where(dw => dw.PluginId == id && dw.WidgetId == i.Id).Any()
                        }).ToArray();
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            else
                return Json(new DashboardWidget[] { }, JsonRequestBehavior.AllowGet);
        }

    }
}
